package xcmg.device.service.sale;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.salesReturn.SalesReturnApplyDO;
import xcmg.device.dao.entity.salesReturn.SalesReturnApplyDetailDO;
import xcmg.device.dao.entity.salesReturn.SalesReturnInDO;
import xcmg.device.dao.entity.salesReturn.SalesReturnInDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDO;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDetailDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.PurchaseRequestMapper;
import xcmg.device.dao.mapper.SaleIntentionMapper;
import xcmg.device.dao.mapper.salesReturn.ReturnApplyDetailMapper;
import xcmg.device.dao.mapper.salesReturn.ReturnApplyMapper;
import xcmg.device.dao.mapper.salesReturn.ReturnInDetailMapper;
import xcmg.device.dao.mapper.salesReturn.ReturnInMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaLocationDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundMapper;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.SalesReturnConstants;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.company.CompanyInfoService;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.device.service.vo.salesReturn.SalesReturnApplyDetailVO;
import xcmg.device.service.vo.salesReturn.SalesReturnInAddDetailVO;
import xcmg.device.service.vo.salesReturn.SalesReturnInAddVO;
import xcmg.device.service.vo.salesReturn.SalesReturnInDetailVO;
import xcmg.device.service.vo.salesReturn.SalesReturnInExportVO;
import xcmg.device.service.vo.salesReturn.SalesReturnInVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundAddVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundDetailVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundVO;
import xcmg.device.service.warehouse.WarehouseInboundService;
import xcmg.device.util.DecimalUtil;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 退货入库
 * Created by LiChangjiang on 2018/3/6 0006.
 */
@Service
public class ReturnInService
{
    @Autowired
    private ReturnInMapper returnInMapper;

    @Autowired
    private ReturnInDetailMapper returnInDetailMapper;
    @Autowired
    private ReturnInDetailService returnInDetailService;

    @Autowired
    private WarehouseInboundService warehouseInboundService;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private ReturnApplyService returnApplyService;

    @Autowired
    private ReturnApplyDetailService returnApplyDetailService;

    @Autowired
    private ReturnApplyMapper returnApplyMapper;

    @Autowired
    private ReturnApplyDetailMapper returnApplyDetailMapper;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private WarehouseInboundMapper warehouseInboundMapper;

    @Autowired
    private WarehouseInboundDetailMapper warehouseInboundDetailMapper;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private SaleIntentionMapper saleIntentionMapper;

    @Autowired
    private PurchaseRequestMapper purchaseRequestMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;
    @Autowired
    private WarehouseAreaLocationDOMapper warehouseAreaLocationDOMapper;

    //更新标识：I  插入（新增）D 删除
    private static final String HEAD_UPDATE_MARK = "VBKZH";
    //SAP退货订单号，删除时传入
    private static final String SAP_ORDER = "RT_VBELN";
    //备件协同管理平台退货订单号
    private static final String RETURN_NO = "VBELN_CRM";
    //销售组织,sapCode
    private static final String SALE_SAP_CODE = "VKORG";
    //销售渠道
    private static final String SALES_CHANNELS = "VTWEG";
    //产品组
    private static final String PRODUCT_GROUP = "SPART";
    //销售订单类型,2160—ZRE和ZRU   2070--ZD10,页面上给选项选择
    private static final String SALE_ORDER_TYPE = "AUART";
    //售达方
    private static final String SOLD_PART = "KUNNR_AG";
    //送达方
    private static final String DELIVERY_PART = "KUNNR_WE";
    //开票方
    private static final String INVOICE_PART = "KUNNR_RE";
    //付款方
    private static final String PAYED_PART = "KUNNR_RG";
    //订单原因（业务原因），退货订单时必输,页面选择
    private static final String RETURN_REASON_CODE = "AUGRU";
    //付款条件,配置，来源于客户主数据，数据字典中，提供选择
    private static final String PAY_CONDITION = "ZTERM";
    //合同编号
    private static final String CONTRACT_NO = "BSTKD";
    //采购日期
    private static final String PURCHASE_DATE = "BSTDK";
    //科技销售信息记录
    private static final String SALES_INFO_RECORD = "INFO";

    //更新标识：I  插入（新增）D 删除
    private static final String DETAIL_UPDATE_MARK = "VBKZL";
    //行号
    private static final String LINE_NO = "POSNR";
    //零件号
    private static final String MATERIALS_NO = "MATNR";
    //数量
    private static final String IN_QTY = "ZMENG";
    //计量单位
    private static final String UNIT = "ZIEME";
    //订单成交价
    private static final String ORDER_PRICE = "KBETR_ZPR4";
    //价格组
    private static final String PRICE_GROUP = "KONDA";
    // sap退货订单号
    private static final String SAP_RETURN_NO_CODE = "VBELN_EXPORT";

    //sap接口函数名
    private static final String FUNCTION_NAME = "ZPMS_BJ_SET_RETURN";
    //sap内部表名
    private static final String SAP_TABLE_NAME = "ITEMS";

    /**
     * 查询退货入库单列表
     *
     * @param condition SearchCommonVO<SalesReturnApplyVO>
     * @return PageCommonVO
     */
    public PageCommonVO list(SearchCommonVO<SalesReturnInVO> condition)
    {
        PageCommonVO<SalesReturnInVO> result = new PageCommonVO<>();
        List<SalesReturnInVO> voList = new ArrayList<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize(), "CREATE_TIME DESC");

        List<SalesReturnInDO> doList = returnInMapper.list(condition.getFilters());
        for (SalesReturnInDO entity : doList)
        {
            voList.add(getVO(entity));
        }
        result.setPageInfo(new PageInfo(doList));
        result.setPageInfoList(voList);
        return result;
    }

    /**
     * 查询退货入库单详细信息
     *
     * @param id String
     * @return SalesReturnApplyVO
     */
    public SalesReturnInVO item(String id)
    {
        SalesReturnInDO salesReturnInDO = returnInMapper.item(id);

        if (null == salesReturnInDO)
        {
            return null;
        }
        SalesReturnInVO salesReturnInVO = getVO(salesReturnInDO);

        //退货入库单详细（零件信息）
        List<SalesReturnInDetailVO> salesReturnInDetailVOs = returnInDetailService.list(salesReturnInDO.getReturnNo(), salesReturnInDO);
        salesReturnInDetailVOs.forEach(x->{
            String loactionCode = x.getStockLocation();
            if (StringUtils.isNotBlank(loactionCode)){
                x.setLocationDesc(warehouseAreaLocationDOMapper.getLocationDesc(loactionCode));
            }
        });
        salesReturnInVO.setReturnInDetailVOs(salesReturnInDetailVOs);

        return salesReturnInVO;
    }

    /**
     * 删除退货单信息
     *
     * @param ids List<String>
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode remove(List<String> ids,String orgId) throws Exception
    {
        if (checkConditionBeforeRemove(ids))
        {
            return ErrorCode.StatusIsIn;
        }

        for (String id : ids)
        {
            SalesReturnInVO salesReturnInVO = item(id);

            if (null == salesReturnInVO)
            {
                continue;
            }

            //更改事务单为作废状态
            warehouseInboundMapper.updateStateNoBarcode(4, salesReturnInVO.getReturnNo(), orgId);

            returnInMapper.remove(salesReturnInVO.getId());
            returnInDetailMapper.removeByNo(salesReturnInVO.getReturnNo());

            List<SalesReturnInDetailVO> salesReturnInDetailVOList = salesReturnInVO.getReturnInDetailVOs();

            if (ListUtil.isNullOrEmpty(salesReturnInDetailVOList))
            {
                continue;
            }

            boolean returnFlag = true;

            //修改退货申请单中退货数量以及申请单状态
            for (SalesReturnInDetailVO inDetailVO : salesReturnInDetailVOList)
            {
                SalesReturnApplyDetailVO applyDetailVO = returnApplyDetailService.itemById(inDetailVO.getApplyDetailId());
                if (null == applyDetailVO)
                {
                    continue;
                }
                SalesReturnApplyDetailDO applyDetailDO = new SalesReturnApplyDetailDO();
                applyDetailDO.setReturnQty(applyDetailVO.getReturnQty().subtract(inDetailVO.getThisReturn()));
                applyDetailDO.setId(applyDetailVO.getId());
                if(applyDetailDO.getReturnQty().compareTo(BigDecimal.ZERO) == 0)
                {
                    applyDetailDO.setIsReturn(SalesReturnConstants.UNDONE_RETURN);
                    returnFlag=false;
                }
                else if(applyDetailDO.getReturnQty().equals(applyDetailDO.getApplyQty()))
                {
                    applyDetailDO.setIsReturn(SalesReturnConstants.DONE_RETURN);
                }
                else
                {
                    applyDetailDO.setIsReturn(SalesReturnConstants.DOING_RETURN);
                    returnFlag=false;
                }
                returnApplyDetailMapper.update(applyDetailDO);
            }

            if(!returnFlag)
            {
                SalesReturnApplyDO applyDO = new SalesReturnApplyDO();
                applyDO.setId(salesReturnInVO.getApplyId());
                applyDO.setIsReturn(SalesReturnConstants.DOING_RETURN);//退货中
                returnApplyMapper.update(applyDO);
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 删除步骤校验，如果有退货单状态为入库，则不可以删除 ,返回TRUE
     *
     * @param ids List<String>
     * @return boolean
     */
    private boolean checkConditionBeforeRemove(List<String> ids)
    {
        for (String id : ids)
        {
            SalesReturnInDO salesReturnInDO = returnInMapper.item(id);
            if (null == salesReturnInDO)
            {
                continue;
            }
            if (0 != salesReturnInDO.getIsIn())
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 修改退货入库单信息
     *
     * @param salesReturnInAddVO SalesReturnInAddVO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode update(SalesReturnInAddVO salesReturnInAddVO) throws Exception
    {
        if (StringUtil.isNullOrSpace(salesReturnInAddVO.getWarehouseCode()) && StringUtil.isNullOrSpace(salesReturnInAddVO.getRemark()) && ListUtil.isNullOrEmpty(salesReturnInAddVO.getReturnInAddDetailVOs()))
        {
            return ErrorCode.Success;
        }
        SalesReturnInDO inDO = returnInMapper.item(salesReturnInAddVO.getId());

        if (null == inDO)
        {
            return ErrorCode.ReturnBillIsNull;
        }

        if (inDO.getIsIn() != 0)
        {
            return ErrorCode.ReturnBillIsIn;
        }

        SalesReturnInDO salesReturnInDO = new SalesReturnInDO();

        salesReturnInDO.setId(salesReturnInAddVO.getId());
        salesReturnInDO.setReturnNo(salesReturnInAddVO.getReturnNo());
        salesReturnInDO.setRemark(salesReturnInAddVO.getRemark());
        salesReturnInDO.setWarehouseCode(salesReturnInAddVO.getWarehouseCode());

        returnInMapper.update(salesReturnInDO);

        //更改业务单信息
        WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(salesReturnInDO.getReturnNo(), salesReturnInAddVO.getOrgId());
        inboundDO.setWarehouseCode(salesReturnInAddVO.getWarehouseCode());
        warehouseInboundMapper.updateByPrimaryKeySelective(inboundDO);

        List<SalesReturnInAddDetailVO> salesReturnInAddDetailVOList = salesReturnInAddVO.getReturnInAddDetailVOs();

        if (ListUtil.isNullOrEmpty(salesReturnInAddDetailVOList))
        {
            return ErrorCode.Success;
        }

        String applyId = "";

        for (SalesReturnInAddDetailVO temp : salesReturnInAddDetailVOList)
        {
            SalesReturnInDetailDO updateDO = new SalesReturnInDetailDO();
            updateDO.setId(temp.getId());
            updateDO.setThisReturn(temp.getThisReturn());
            SalesReturnInDetailDO inDetailDO = returnInDetailMapper.itemById(temp.getId());
            if (null == inDetailDO)
            {
                continue;
            }
            if(inDetailDO.getStatus()==2||inDetailDO.getStatus()==3)
            {
                continue;//已完成入库或者结单的零件，不可以编辑
            }
            if (inDetailDO.getThisReturn().equals(temp.getThisReturn()))
            {
                continue;
            }
            SalesReturnApplyDetailDO applyDetailDO = returnApplyDetailMapper.itemById(inDetailDO.getApplyDetailId());

            if (null == applyDetailDO)
            {
                return ErrorCode.SalesReturnApplyIsNull;
            }

            applyId = applyDetailDO.getApplyId();

            //本次修改之后的退货数量=（原申请表中已退货数量-上次退货数量）+本次退货数量
            BigDecimal returnQty = applyDetailDO.getReturnQty().subtract(inDetailDO.getThisReturn()).add(temp.getThisReturn());
            if (returnQty.compareTo(applyDetailDO.getApplyQty()) > 0)
            {
                throw new Exception("零件" + inDetailDO.getMaterialsNo() + "退货数量错误！");
            }

            WarehouseInboundDetailDO inboundDetailDO = warehouseInboundDetailMapper.selectByNo(salesReturnInAddVO.getReturnNo(), temp.getMaterialsNo(), salesReturnInAddVO.getOrgId());

            if(null!=inboundDetailDO&& inboundDetailDO.getPrintNum()!=null)
            {
                if (returnQty.compareTo(inboundDetailDO.getPrintNum()) < 0)
                {
                    return ErrorCode.AbnormalInUpdateError;
                }
            }

            applyDetailDO.setReturnQty(returnQty);
            returnApplyDetailMapper.update(applyDetailDO);
            returnInDetailMapper.update(updateDO);

            WarehouseInboundDetailDO warehouseInboundDetailDO = new WarehouseInboundDetailDO();
            warehouseInboundDetailDO.setAmount(returnQty);
            warehouseInboundDetailDO.setMaterialNo(temp.getMaterialsNo());
            warehouseInboundDetailDO.setBusinessOrder(salesReturnInAddVO.getReturnNo());
            warehouseInboundDetailMapper.updateAmountByNo(warehouseInboundDetailDO);
        }

        ErrorCode updateCode = returnApplyService.updateReturnStatus(applyId);

        return ErrorCode.Success;
    }

    /**
     * 添加退货入库信息<br>
     *
     * @param salesReturnInAddVO SalesReturnInAddVO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode insert(SalesReturnInAddVO salesReturnInAddVO,String depyName) throws Exception
    {
        SalesReturnApplyDO salesReturnApplyDO = returnApplyMapper.itemByNo(salesReturnInAddVO.getApplyNo());

        if (null == salesReturnApplyDO || !SalesReturnConstants.APPLY_STATUS_PASS.equals(salesReturnApplyDO.getStatus()))
        {
            return ErrorCode.IllegalArument;
        }

        if (SalesReturnConstants.DONE_RETURN.equals(salesReturnApplyDO.getIsReturn()))
        {
            return ErrorCode.SalesIsReturn;
        }

        salesReturnInAddVO.setApplyId(salesReturnApplyDO.getId());

        List<SalesReturnApplyDetailDO> applyDetailDOs = returnApplyDetailMapper.list(salesReturnInAddVO.getApplyId());

        List<SalesReturnInDetailVO> salesReturnInDetailVOs = new ArrayList<>();

        //获取退货入库DO
        SalesReturnInDO salesReturnInDO = getSalesReturnInDO(salesReturnInAddVO);
        salesReturnInDO.setDept(depyName);
        int ret = returnInMapper.insert(salesReturnInDO);
        if (0 >= ret)
        {
            return ErrorCode.SqlSyntaxError;
        }

        List<SalesReturnInAddDetailVO> salesReturnInAddDetailVOs = salesReturnInAddVO.getReturnInAddDetailVOs();

        //退货类型标识，false：部分退货  true：全部退货
        boolean returnFlag = true;

        returnFlag = checkSalesReturn(applyDetailDOs, salesReturnInAddDetailVOs);

        for (SalesReturnInAddDetailVO addDetailVO : salesReturnInAddDetailVOs)
        {
            SalesReturnApplyDetailVO returnApplyDetailVO = returnApplyDetailService.itemById(addDetailVO.getId());
            if (null == returnApplyDetailVO)
            {
                throw new Exception("退货失败！");
            }

            SalesReturnInDetailVO returnInDetailVO = new SalesReturnInDetailVO();
            returnInDetailVO.setMaterialsNo(returnApplyDetailVO.getMaterialsNo());
            returnInDetailVO.setMaterialsType(returnApplyDetailVO.getMaterialsType());
            returnInDetailVO.setMaterialsDes(returnApplyDetailVO.getMaterialsDes());
            returnInDetailVO.setUnit(returnApplyDetailVO.getUnit());
            returnInDetailVO.setThisReturn(addDetailVO.getThisReturn());
            returnInDetailVO.setInQty(BigDecimal.ZERO);
            returnInDetailVO.setApplyDetailId(returnApplyDetailVO.getId());
            returnInDetailVO.setPriceSchemeId(addDetailVO.getPriceSchemeId());
            returnInDetailVO.setPriceSchemeName(addDetailVO.getPriceSchemeName());
            returnInDetailVO.setPrice(addDetailVO.getPrice());

            //            if(addDetailVO.getThisReturn() <= 0)
            //            {
            //                throw new Exception("零件"+returnApplyDetailVO.getMaterialsNo()+"退货数量错误！");
            //            }
            BigDecimal temp = returnApplyDetailVO.getApplyQty().subtract(returnApplyDetailVO.getReturnQty()).subtract(addDetailVO.getThisReturn());
            if (temp.compareTo(BigDecimal.ZERO) < 0)
            {
                throw new Exception("零件" + returnApplyDetailVO.getMaterialsNo() + "退货数量错误！");
            }

            //判断退货申请单零件数量与退货数量是否相等
            if (temp.compareTo(BigDecimal.ZERO) > 0)
            {
                returnFlag = false;
            }

            SalesReturnApplyDetailVO applyDetailVO = new SalesReturnApplyDetailVO();
            applyDetailVO.setId(addDetailVO.getId());
            applyDetailVO.setReturnQty(returnApplyDetailVO.getReturnQty().add(addDetailVO.getThisReturn()));//已退货数量+本次退货数量
            returnApplyDetailService.update(applyDetailVO);

            salesReturnInDetailVOs.add(returnInDetailVO);
        }

        SalesReturnApplyDO updateBean = new SalesReturnApplyDO();
        if (!returnFlag)
        {
            updateBean.setIsReturn(SalesReturnConstants.DOING_RETURN);//退货中
            updateBean.setId(salesReturnInAddVO.getApplyId());
            returnApplyMapper.update(updateBean);//修改退货申请单
        }
        else
        {
            updateBean.setIsReturn(SalesReturnConstants.DONE_RETURN);//退货完成
            updateBean.setId(salesReturnInAddVO.getApplyId());
            returnApplyMapper.update(updateBean);//修改退货申请单
        }

        //添加退货入库单零件信息
        ErrorCode inDetailAddCode = returnInDetailService.add(salesReturnInDetailVOs, salesReturnInDO.getReturnNo());

        if (ErrorCode.Success != inDetailAddCode)
        {
            return inDetailAddCode;
        }

        //生成入库单事物表信息
        WarehouseInboundAddVO addVO = getWarehouseInboundAddVO(salesReturnInDO, salesReturnInDetailVOs);

        //添加入库业务完成之后，添加入库事物单信息
        return warehouseInboundService.add(addVO, salesReturnInAddVO.getUserId(), salesReturnInAddVO.getOrgId());
    }

    /**
     * 校验前端传的零件集合是否将退货申请单全部退货，如果是全部退货，返回TRUE
     *
     * @param applyDetailDOs            List<SalesReturnApplyDetailDO> 退货申请零件列表信息
     * @param salesReturnInAddDetailVOs List<SalesReturnInAddDetailVO>  需要退货的零件列表信息
     * @return boolean 两个集合中ID完全一致则返回TRUE
     */
    private boolean checkSalesReturn(List<SalesReturnApplyDetailDO> applyDetailDOs, List<SalesReturnInAddDetailVO> salesReturnInAddDetailVOs)
    {
        List<String> applyDetailIds = new ArrayList<>();
        List<String> inDetailIds = new ArrayList<>();

        //获取所有需要退货的零件ID集合
        for (SalesReturnInAddDetailVO addDetailVO : salesReturnInAddDetailVOs)
        {
            inDetailIds.add(addDetailVO.getId());
        }
        Set<String> idSet = new HashSet<>();
        idSet.addAll(inDetailIds);
        int inSetSize = idSet.size();

        //获取所有退货申请中的零件ID集合
        for (SalesReturnApplyDetailDO applyDetailDO : applyDetailDOs)
        {
            applyDetailIds.add(applyDetailDO.getId());
        }
        idSet.addAll(applyDetailIds);

        int totalSize = idSet.size();

        //比较set长度是否改变
        if (inSetSize == totalSize)
        {
            return true;
        }
        return false;
    }


    /**
     * 获取退货入库DO
     *
     * @param salesReturnInAddVO SalesReturnInAddVO
     * @return SalesReturnInDO
     * @throws Exception Exception
     */
    private SalesReturnInDO getSalesReturnInDO(SalesReturnInAddVO salesReturnInAddVO) throws Exception
    {
        SalesReturnInDO salesReturnInDO = new SalesReturnInDO();

        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult == null || textResult.getCode() != 0)
        {
            throw new Exception("生成退货单ID失败!");
        }
        String returnId = textResult.getValue();

        String returnNo = genDocumentService.getDocumentNo(BillDesc.SaleReturn); //退货单号

        salesReturnInDO.setId(returnId);
        salesReturnInDO.setApplyId(salesReturnInAddVO.getApplyId());
        salesReturnInDO.setApplyNo(salesReturnInAddVO.getApplyNo());
        salesReturnInDO.setReturnNo(returnNo);
        salesReturnInDO.setUserId(salesReturnInAddVO.getUserId());
        salesReturnInDO.setUserName(salesReturnInAddVO.getUserName());
        salesReturnInDO.setOrgId(salesReturnInAddVO.getOrgId());
        CompanyInfoVO companyInfoVO = companyInfoService.info(salesReturnInAddVO.getOrgId());
        salesReturnInDO.setOrgName(companyInfoVO.getCompanyName());
        salesReturnInDO.setWarehouseCode(salesReturnInAddVO.getWarehouseCode());
        salesReturnInDO.setRemark(salesReturnInAddVO.getRemark());
        salesReturnInDO.setInArea(salesReturnInAddVO.getInArea());
        salesReturnInDO.setSapInArea(salesReturnInAddVO.getSapInArea());
        return salesReturnInDO;
    }

    /**
     * 添加退货入库单
     *
     * @param returnInVO SalesReturnInVO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(SalesReturnInVO returnInVO) throws Exception
    {
        if (ListUtil.isNullOrEmpty(returnInVO.getReturnInDetailVOs()))
        {
            return ErrorCode.IllegalArument;
        }
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult == null || textResult.getCode() != 0)
        {
            return ErrorCode.Failure;
        }
        String returnId = String.valueOf(textResult.getValue());

        String returnNo = genDocumentService.getDocumentNo(BillDesc.SaleReturn); //退货单号

        SalesReturnInDO returnInDO = getDO(returnInVO);

        returnInDO.setId(returnId);
        returnInDO.setReturnNo(returnNo);

        //添加退货入库单信息
        int addRet = returnInMapper.insert(returnInDO);

        if (0 >= addRet)
        {
            return ErrorCode.SalesReturnAddFail;
        }

        //添加退货入库单零件信息
        ErrorCode inDetailAddCode = returnInDetailService.add(returnInVO.getReturnInDetailVOs(), returnNo);

        if (ErrorCode.Success != inDetailAddCode)
        {
            return inDetailAddCode;
        }

        //生成入库单事物表信息
        WarehouseInboundAddVO addVO = getWarehouseInboundAddVO(returnInDO, returnInVO.getReturnInDetailVOs());

        //添加入库业务完成之后，添加入库事物单信息
        return warehouseInboundService.add(addVO, returnInVO.getUserId(), returnInVO.getOrgId());
    }

    /**
     * 生成入库单信息
     *
     * @param returnInDO           SalesReturnInVO
     * @param returnInDetailVOList List<SalesReturnInDetailVO>
     * @return WarehouseInboundAddVO
     */
    private WarehouseInboundAddVO getWarehouseInboundAddVO(SalesReturnInDO returnInDO, List<SalesReturnInDetailVO> returnInDetailVOList)
    {
        WarehouseInboundAddVO addVO = new WarehouseInboundAddVO();
        WarehouseInboundVO headVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailVOList = new ArrayList<>();

        String businessSingle = returnInDO.getReturnNo().substring(0, 4);
        String businessOrder = returnInDO.getReturnNo();

        headVO.setBusinessSingle(businessSingle);
        headVO.setBusinessOrder(businessOrder);
        headVO.setWarehouseCode(returnInDO.getWarehouseCode());
        headVO.setInArea(returnInDO.getInArea());
        headVO.setSapInArea(returnInDO.getSapInArea());

        BigDecimal num = BigDecimal.ZERO;
        if (!ListUtil.isNullOrEmpty(returnInDetailVOList))
        {
            for (SalesReturnInDetailVO inDetailVO : returnInDetailVOList)
            {
                WarehouseInboundDetailVO addDetailVO = new WarehouseInboundDetailVO();
                addDetailVO.setBusinessSingle(businessSingle);
                addDetailVO.setBusinessOrder(businessOrder);
                addDetailVO.setMaterialNo(inDetailVO.getMaterialsNo());
                addDetailVO.setMaterialName(inDetailVO.getMaterialsDes());
                addDetailVO.setMaterialType(inDetailVO.getMaterialsType());
                addDetailVO.setUnit(inDetailVO.getUnit());
                addDetailVO.setAmount(inDetailVO.getThisReturn());
                addDetailVO.setRealAmount(BigDecimal.ZERO);
                num = num.add(inDetailVO.getThisReturn());
                detailVOList.add(addDetailVO);
            }
        }
        headVO.setAmount(num);
        addVO.setHeaderInfo(headVO);
        addVO.setDetailList(detailVOList);
        return addVO;
    }


    /**
     * 新增入库记录时，同时更新退货入库单和退货入库零件信息<br>
     * 事务单状态为退货完成或强制完成，业务单状态则为退货完成
     *
     * @param returnNo    String 退货入库单号
     * @param materialNo  String 零件编号
     * @param realAmount  String 真实入库数量
     * @param singelState Integer 零件状态
     * @param totalState  Integer 入库单状态
     * @return boolean “true” is success
     * @throws Exception Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByInbound(String returnNo, String materialNo, BigDecimal realAmount, Integer singelState, Integer totalState) throws Exception
    {
        SalesReturnInDetailVO detailVO = new SalesReturnInDetailVO();
        detailVO.setReturnNo(returnNo);
        detailVO.setMaterialsNo(materialNo);
        SalesReturnInDetailDO inDetailDO = returnInDetailMapper.item(returnNo, materialNo);
        if (null == inDetailDO)
        {
            return false;
        }
        if (realAmount.compareTo(inDetailDO.getThisReturn()) > 0)
        {
            throw new Exception("实际入库数量不能大于计划入库数量");
        }
        inDetailDO.setInQty(realAmount);
        inDetailDO.setStatus(singelState);
        boolean success = returnInDetailMapper.update(inDetailDO) > 0;
        if (success)
        {
            SalesReturnInDO returnInDO = returnInMapper.itemByNo(returnNo);
            if (null == returnInDO)
            {
                return false;
            }
            if (totalState == 2 || totalState == 3)
            {
                returnInDO.setStatus(2);
                returnInDO.setIsIn(2);
                returnInMapper.update(returnInDO);

                //入库单完成状态，更新退货申请单、销售意向单、发货通知单
                returnApplyService.salesReturnInSuccess(returnInDO, materialNo, realAmount);
            }
            else if (totalState == 1)   //入库中，即部分完成
            {
                returnInDO.setStatus(1);
                returnInDO.setIsIn(1);
                returnInMapper.update(returnInDO);

                //入库单完成状态，更新退货申请单、销售意向单、发货通知单
                returnApplyService.salesReturnInSuccess(returnInDO, materialNo, realAmount);
            }
        }
        return success;
    }

    /**
     * 导出所选入库单
     *
     * @param ids List 入库单ID集合
     * @throws Exception Exception
     */
    public void export(List<String> ids) throws Exception
    {
        List<SalesReturnInExportVO> exportVOList = new ArrayList<>();
        List<SalesReturnInVO> returnInVOs = new ArrayList<>();
        for (String id : ids)
        {
            SalesReturnInVO salesReturnInVO = item(id);
            returnInVOs.add(salesReturnInVO);

//            if (null == salesReturnInVO)
//            {
//                invokeExport(exportVOList);
//                return;
//            }
//
//            List<SalesReturnInDetailVO> detailVOList = returnInDetailService.list(salesReturnInVO.getReturnNo());
//            if (ListUtil.isNullOrEmpty(detailVOList))
//            {
//                exportVOList.add(getExportVO(salesReturnInVO, null));
//                continue;
//            }
//
//            for (SalesReturnInDetailVO detailVO : detailVOList)
//            {
//                //封装导出所需的VO对象
//                exportVOList.add(getExportVO(salesReturnInVO, detailVO));
//            }
        }
        invokeExport(returnInVOs);
    }


    /**
     * 导出（当前企业）全部入库单集合
     *
     * @param condition SalesReturnInVO
     * @throws Exception Exception
     */
    public void exportAll(SalesReturnInVO condition) throws Exception
    {
        SearchCommonVO<SalesReturnInVO> returnInVOSearchCommonVO = new SearchCommonVO<>();
        returnInVOSearchCommonVO.setFilters(condition);
        returnInVOSearchCommonVO.setPageNum(0);
        returnInVOSearchCommonVO.setPageSize(0);

        //查询所有记录
        PageCommonVO pageCommonVO = this.list(returnInVOSearchCommonVO);
        List<SalesReturnInVO> returnInVOs = pageCommonVO.getPageInfoList();

//        //循环退货入库信息，查询出对应的零件信息
//        for (SalesReturnInVO returnInVO : returnInVOs)
//        {
//            List<SalesReturnInDetailVO> detailVOList = returnInDetailService.list(returnInVO.getReturnNo());
//
//            if (ListUtil.isNullOrEmpty(detailVOList))
//            {
//                exportVOList.add(getExportVO(returnInVO, null));
//                continue;
//            }
//
//            for (SalesReturnInDetailVO detailVO : detailVOList)
//            {
//                exportVOList.add(getExportVO(returnInVO, detailVO));
//            }
//        }
        invokeExport(returnInVOs);
    }

    /**
     * 导出退货入库单
     *
     * @param exportVOs List
     * @throws Exception Exception
     */
    private void invokeExport(List<SalesReturnInVO> exportVOs) throws Exception
    {
        String title = "退货入库单导出";
        String[] rowsName = new String[]{"序号", "退货入库单号", "退货申请单号", "制单人","制单部门", "制单时间", "调入仓库","调入库区", "状态","备注"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;

        if (ListUtil.isNullOrEmpty(exportVOs))
        {
            ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
            exportUtil.export(response);
            return;
        }
        for (int i = 0; i < exportVOs.size(); i++)
        {
            SalesReturnInVO e = exportVOs.get(i);

            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = e.getReturnNo();
            objs[2] = e.getApplyNo();
            objs[3] = e.getCreateName();
            objs[4] = e.getDept();
            objs[5] = DateUtil.formatDateTime(e.getCreateTime());
            objs[6] = e.getWarehouseCode();
            objs[7] = e.getInArea();
            objs[8] = e.getIsInDesc();
            objs[9] = e.getRemark();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }


    /**
     * @param beanVO SalesReturnApplyVO
     * @return SalesReturnApplyDO
     */
    private SalesReturnInDO getDO(SalesReturnInVO beanVO)
    {
        if (null == beanVO)
        {
            return null;
        }
        SalesReturnInDO beanDO = new SalesReturnInDO();

        beanDO.setId(beanVO.getId());
        beanDO.setApplyId(beanVO.getApplyId());
        beanDO.setReturnNo(beanVO.getReturnNo());
        beanDO.setUserId(beanVO.getCreateId());
        beanDO.setUserName(beanVO.getCreateName());
        beanDO.setOrgId(beanVO.getOrgId());
        beanDO.setOrgName(beanVO.getOrgName());
        beanDO.setCreateTime(beanVO.getCreateTime());
        beanDO.setUpdateTime(beanVO.getUpdateTime());
        beanDO.setStatus(beanVO.getStatus());
        beanDO.setIsIn(beanVO.getIsIn());
        beanDO.setWarehouseCode(beanVO.getWarehouseCode());
        beanDO.setApplyNo(beanVO.getReturnNo());
        beanDO.setRemark(beanVO.getRemark());
        beanDO.setDept(beanVO.getDept());
        beanDO.setInArea(beanVO.getInArea());
        beanDO.setSapInArea(beanVO.getSapInArea());
        beanDO.setPostingState(beanVO.getPostingState());
        beanDO.setSapErrorMsg(beanVO.getSapErrorMsg());
        beanDO.setSapOrderNo(beanVO.getSapOrderNo());
        return beanDO;
    }

    /**
     * @param beanDO SalesReturnApplyDO
     * @return SalesReturnApplyVO
     */
    private SalesReturnInVO getVO(SalesReturnInDO beanDO)
    {
        if (null == beanDO)
        {
            return null;
        }
        SalesReturnInVO beanVO = new SalesReturnInVO();

        beanVO.setId(beanDO.getId());
        beanVO.setApplyId(beanDO.getApplyId());
        beanVO.setReturnNo(beanDO.getReturnNo());
        beanVO.setCreateId(beanDO.getUserId());
        beanVO.setCreateName(beanDO.getUserName());
        beanVO.setOrgId(beanDO.getOrgId());
        beanVO.setOrgName(beanDO.getOrgName());
        beanVO.setCreateTime(beanDO.getCreateTime());
        beanVO.setUpdateTime(beanDO.getUpdateTime());
        beanVO.setStatus(beanDO.getStatus());
        beanVO.setWarehouseCode(beanDO.getWarehouseCode());
        beanVO.setIsIn(beanDO.getIsIn());
        beanVO.setBillTypeName("退货入库");
        beanVO.setApplyNo(beanDO.getApplyNo());
        beanVO.setRemark(beanDO.getRemark());
        beanVO.setDept(beanDO.getDept());
        beanVO.setInArea(beanDO.getInArea());
        beanVO.setSapInArea(beanDO.getSapInArea());
        beanVO.setPostingState(beanDO.getPostingState());
        beanVO.setSapErrorMsg(beanDO.getSapErrorMsg());
        beanVO.setSapOrderNo(beanDO.getSapOrderNo());
        //0待审核，1审核拒绝，2审核通过
        if (1 == beanDO.getStatus())
        {
            beanVO.setStatusDesc("部分完成");
        }
        else if (2 == beanDO.getStatus())
        {
            beanVO.setStatusDesc("完成");
        }
        else if (3 == beanDO.getStatus())
        {
            beanVO.setStatusDesc("强制完成");
        }
        else
        {
            beanVO.setStatusDesc("未完成");
        }


        if (1 == beanDO.getIsIn())
        {
            beanVO.setIsInDesc("部分入库");
        }
        else if (2 == beanDO.getIsIn())
        {
            beanVO.setIsInDesc("入库完成");
        }
        else if (3 == beanDO.getIsIn())
        {
            beanVO.setIsInDesc("强制结单");
        }
        else
        {
            beanVO.setIsInDesc("未入库");
        }
        return beanVO;
    }


    public SalesReturnInExportVO getExportVO(SalesReturnInVO returnInVO, SalesReturnInDetailVO returnInDetailVO)
    {
        SalesReturnInExportVO exportVO = new SalesReturnInExportVO();
        if (null != returnInVO)
        {
            exportVO.setApplyId(returnInVO.getApplyId());
            exportVO.setReturnNo(returnInVO.getReturnNo());
            exportVO.setUserName(returnInVO.getUserName());
            exportVO.setOrgId(returnInVO.getOrgId());
            exportVO.setOrgName(returnInVO.getOrgName());
            exportVO.setCreateTime(returnInVO.getCreateTime());
            exportVO.setStatusDesc(returnInVO.getStatusDesc());
            exportVO.setDept(returnInVO.getDept());
        }
        if (null != returnInDetailVO)
        {
            exportVO.setDetailId(returnInDetailVO.getId());
            exportVO.setMaterialsNo(returnInDetailVO.getMaterialsNo());
            exportVO.setMaterialsType(returnInDetailVO.getMaterialsType());
            exportVO.setMaterialsDes(returnInDetailVO.getMaterialsDes());
            exportVO.setUnit(returnInDetailVO.getUnit());
            exportVO.setQty(returnInDetailVO.getThisReturn());
            exportVO.setRealQty(returnInDetailVO.getInQty());
            exportVO.setDetailStatusDesc(returnInDetailVO.getStatusDesc());
        }

        return exportVO;
    }

    /**
     * 手动完成单据<br>
     *     materialsNo 不为null,则更改该单据下的零件状态为“手动完成”状态；如果materialsNo为空，则更改整个单据为“手动完成”状态
     * @param billNo  String 单据编号
     * @param materialsNo String 零件编号
     * @param orgId String 企业ID
     * @return ErrorCode 返回码
     */
    public ErrorCode manualFinish(String billNo,String materialsNo,String orgId)
    {
        SalesReturnInDO returnInDO = returnInMapper.itemByNo(billNo);

        if (StringUtil.isNullOrEmpty(materialsNo))//零件编码为空，更新单据状态为“手动完成”
        {
            returnInDO.setStatus(3);
            returnInDO.setIsIn(3);
            returnInMapper.update(returnInDO);

            //入库单完成状态，更新退货申请单、销售意向单、发货通知单
            returnApplyService.manualFinishReturnIn(returnInDO);

            warehouseInboundService.updateState(billNo,3,orgId);

            returnInDetailMapper.updateStatus(3,billNo,null);
            warehouseInboundDetailMapper.updateAllStatus(3, billNo, orgId);
        }
        else
        {
            returnInDetailMapper.updateStatus(3,billNo,materialsNo);
            warehouseInboundService.updateDetailState(billNo,materialsNo,null,3,orgId);
            ErrorCode errorCode = checkBillFinished(billNo,orgId);

            if(ErrorCode.Success!=errorCode)
            {
                return errorCode;
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 校验单据是否已完成<br>
     *     判断单据下的所有零件是否已经完成，如果都完成，则更改单据状态为完成
     * @param billNo String
     * @param orgId String
     * @return Boolean
     */
    private ErrorCode checkBillFinished(String billNo,String orgId)
    {
        boolean flag = true;
        List<SalesReturnInDetailDO> returnInDetailDOs = returnInDetailMapper.list(billNo);
        for (SalesReturnInDetailDO temp : returnInDetailDOs)
        {
            if (2==temp.getStatus() || 3==temp.getStatus())
            {
                //完成状态
                continue;
            }
            flag =false;
        }

        if(flag)
        {
            SalesReturnInDO returnInDO = returnInMapper.itemByNo(billNo);

            returnInDO.setStatus(3);
            returnInDO.setIsIn(3);
            returnInMapper.update(returnInDO);

            //入库单完成状态，更新退货申请单、销售意向单、发货通知单
            returnApplyService.manualFinishReturnIn(returnInDO);

            warehouseInboundService.updateState(billNo,3,orgId);
        }
        return ErrorCode.Success;
    }

//    /**
//     * 退货入库过账
//     */
//    public ErrorCode sapPost(SalesReturnInVO salesReturnInVO, String orgId) throws Exception {
//        SalesReturnInDO salesReturnInDO = returnInMapper.item(salesReturnInVO.getId());
//        if (salesReturnInDO == null) {
//            return ErrorCode.ImportExcelNoData;
//        }
//        if (salesReturnInDO.getPostingState() == 1) {
//            throw new Exception("该退货入库已过账");
//        }
//
//        ImportParam importParam = fillImportParam(salesReturnInDO, 1, orgId);
//        LogHelper.monitor("========调用退货入库过账接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用退货入库过账接口结束========");
//        if (null == outputParam || outputParam.getCode() != 0) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("sap返回值为null");
//        }
//
//        if ("OK".equals(outputParam.getDataHeader().get("RETURNCODE").toUpperCase())) {
//            if(StringUtil.isNullOrEmpty(outputParam.getDataHeader().get(SAP_RETURN_NO_CODE))){
//                throw new Exception("sap退货订单号为null");
//            }
//            SalesReturnInDO returnIn = new SalesReturnInDO();
//            returnIn.setId(salesReturnInVO.getId());
//            returnIn.setPostingState((short)1);
//            // sap退货订单号
//            returnIn.setSapOrderNo(outputParam.getDataHeader().get(SAP_RETURN_NO_CODE));
//            if (returnInMapper.update(returnIn) > 0) {
//                return ErrorCode.Success;
//            }
//            return ErrorCode.Failure;
//        } else {
//            SalesReturnInDO returnIn = new SalesReturnInDO();
//            returnIn.setId(salesReturnInVO.getId());
//            returnIn.setPostingState((short)2);
//            // sap退货订单号
//            returnIn.setSapErrorMsg(outputParam.getDataHeader().get("RETURNMSG"));
//            returnInMapper.update(returnIn);
//            //返回处理的消息
//            throw new Exception(outputParam.getDataHeader().get("RETURNMSG"));
//        }
//    }
//
//    public ErrorCode sapRemove(SalesReturnInVO salesReturnInVO, String orgId) throws Exception {
//        SalesReturnInDO salesReturnInDO = returnInMapper.item(salesReturnInVO.getId());
//        if (salesReturnInDO == null) {
//            return ErrorCode.ImportExcelNoData;
//        }
//        if (salesReturnInDO.getPostingState() == 0) {
//            throw new Exception("该退货入库未过账");
//        }
//
//        ImportParam importParam = fillImportParam(salesReturnInDO, 2, orgId);
//        LogHelper.monitor("========调用退货入库删除过账接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用退货入库删除过账接口结束========");
//        if (null == outputParam || outputParam.getCode() != 0) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("sap返回值为null");
//        }
//
//        if ("OK".equals(outputParam.getDataHeader().get("RETURNCODE").toUpperCase())) {
//            SalesReturnInDO returnIn = new SalesReturnInDO();
//            returnIn.setId(salesReturnInVO.getId());
//            returnIn.setPostingState((short)0);
//            if (returnInMapper.update(returnIn) > 0) {
//                return ErrorCode.Success;
//            }
//            return ErrorCode.Failure;
//        } else {
//            SalesReturnInDO returnIn = new SalesReturnInDO();
//            returnIn.setId(salesReturnInVO.getId());
//            // sap退货订单号
//            returnIn.setSapErrorMsg(outputParam.getDataHeader().get("RETURNMSG"));
//            returnInMapper.update(returnIn);
//            //返回处理的消息
//            throw new Exception(outputParam.getDataHeader().get("RETURNMSG"));
//        }
//    }
//
//    /**
//     * 销售部门销售代表处客户组不填,价格组 从意向订单里面取 就是价格方案的编码，售达方,送达方,开票方,付款方 都是SAP客户编码，付款条件从意向订单里面取
//     * @param salesReturnInDO
//     * @return
//     * @throws Exception
//     */
//    private ImportParam fillImportParam(SalesReturnInDO salesReturnInDO, int type, String orgId) throws Exception {
//        CompanyInfoVO companyInfoVO = companyInfoService.info(salesReturnInDO.getOrgId());
//        if (companyInfoVO == null || companyInfoVO.getSapCode() == null) {
//            LogHelper.error("同步sap过账时企业不存在,orgId:" + salesReturnInDO.getOrgId(), ErrorCode.RequestIdError.getCode());
//            throw new Exception("同步sap过账时企业不存在");
//        }
//
//        if (null == companyInfoVO.getSapCode()) {
//            throw new Exception("同步sap过账时企业SAP编码不存在");
//        }
//
//        SalesReturnApplyDO applyDO = returnApplyMapper.item(salesReturnInDO.getApplyId());
//        if(applyDO == null){
//            throw new Exception("退货申请单不存在");
//        }
//        if(type == 2 && StringUtil.isNullOrEmpty(salesReturnInDO.getSapOrderNo())){
//            throw new Exception("sap退货订单号为空");
//        }
//        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(orgId, applyDO.getPurchaseOrgId());
//        if(companyDealerDO == null||companyDealerDO.getDealerCode()==null){
//            throw new Exception("采购企业不存在或其SAPCODE不存在");
//        }
//       /* CompanyInfoVO purCom = companyInfoService.info(applyDO.getPurchaseOrgId());
//        if(purCom == null){
//            purCom = companyInfoService.info(companyDealerDO.getPlatOrgId());
//        }
//        if (null == purCom || StringUtils.isBlank(purCom.getSapCode())) {
//            throw new Exception("采购企业或其sapCode不存在");
//        }*/
//        ImportParam importParam = new ImportParam();
//        importParam.setFunction(FUNCTION_NAME);
//        // 以下魔法值均为sap开发人员给的默认值
//        Map<String, String> map = new HashMap<>(32);
//        map.put(HEAD_UPDATE_MARK, type==1?"I":"D");
//        if(type == 2){
//            map.put(SAP_ORDER, salesReturnInDO.getSapOrderNo());
//        }
//        map.put(RETURN_NO, salesReturnInDO.getReturnNo());
//        map.put(SALE_SAP_CODE, companyInfoVO.getSapCode());
//        map.put(SALES_CHANNELS, "10");
//        map.put(PRODUCT_GROUP, "10");
//        map.put(SALE_ORDER_TYPE, applyDO.getReturnCategoryCode());
//        map.put(SOLD_PART, companyDealerDO.getDealerCode());
//        map.put(DELIVERY_PART, companyDealerDO.getDealerCode());
//        map.put(INVOICE_PART, companyDealerDO.getDealerCode());
//        map.put(PAYED_PART, companyDealerDO.getDealerCode());
//        map.put(RETURN_REASON_CODE, applyDO.getReturnReasonCode());
//        map.put(PAY_CONDITION, applyDO.getPayConditionCode());
//        map.put(SALES_INFO_RECORD, salesReturnInDO.getRemark());
//        importParam.setCommonParamMap(map);
//        Map<String, List<Map<String, String>>> tableParamMap = new HashMap<>();
//        tableParamMap.put(SAP_TABLE_NAME, getParamList(salesReturnInDO.getReturnNo(), type));
//        importParam.setTableParamMap(tableParamMap);
//        importParam.setSapCode(companyInfoVO.getSapCode());
//        return importParam;
//    }

    private List<Map<String, String>> getParamList(String salesReturnNo, int type) throws Exception {
        List<SalesReturnInDetailDO> detailDOList = returnInDetailMapper.list(salesReturnNo);
        if (CollectionUtils.isEmpty(detailDOList)) {
            LogHelper.monitor("退货入库明细数据为空。salesReturnNo：" + salesReturnNo);
            throw new Exception("退货入库明细数据为空");
        }
        List<Map<String, String>> list = new ArrayList<>();
        for (int i=1;i<=detailDOList.size();i++) {
            SalesReturnInDetailDO detailDO = detailDOList.get(i-1);
            Map<String, String> mapd = new HashMap<>();
            mapd.put(DETAIL_UPDATE_MARK, type==1?"I":"D");
            mapd.put(LINE_NO, "00"+10*i);
            mapd.put(MATERIALS_NO, detailDO.getMaterialsNo());
            mapd.put(IN_QTY, String.valueOf(detailDO.getInQty()));
            mapd.put(UNIT, detailDO.getUnit());
            if(detailDO.getPrice() != null){
                mapd.put(ORDER_PRICE, DecimalUtil.getDecimal(detailDO.getPrice())+"");
            }
            list.add(mapd);
        }
        return list;
    }

    public SalesReturnInDetailDO getSalesReturnInDetailDO(String returnNo, String materialNo) throws Exception
    {
        return returnInDetailMapper.item(returnNo, materialNo);
    }
}
